package com.hongshan.wallet.core.bankcard

import android.app.Application
import android.databinding.ObservableField
import android.view.View
import com.hongshan.wallet.Constant
import com.hongshan.wallet.MyApplication
import com.hongshan.wallet.base.MyViewModel
import com.hongshan.wallet.core.wallet.RealNameActivity
import com.hongshan.wallet.http.HttpClient
import com.hongshan.wallet.toast
import com.hongshan.wallet.tryRun
import com.hongshan.wallet.util.AutoInject
import com.hongshan.wallet.util.MyActivityManager
import com.hongshan.wallet.util.goSetPwd
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.core.bankcard
 * @author   : zhangxx
 * @date     : 2019/4/1
 * @email    : qq957413212@hotmail.com
 * @desc     : //TODO
 */
class AddBankCardViewModel(application: Application) : MyViewModel(application) {

    val name = ObservableField("")
    val cardNum = ObservableField("")
    val tel = ObservableField("")

    @AutoInject(Constant.ROUTE_PARAMS_KEY.REAL_NAME_NAME)
    val realName: String = ""
    @AutoInject(Constant.ROUTE_PARAMS_KEY.REAL_NAME_ID_CARD)
    val idCard: String = ""

    val next = View.OnClickListener {
        val nameStr = name.get()?.trim()
        val telStr = tel.get()?.trim()
        if (nameStr.isNullOrBlank()) {
            toast("请输入正确姓名")
            return@OnClickListener
        }
        val cardNumStr = cardNum.get()
        if (cardNumStr == null || cardNumStr.length < 16 || cardNumStr.length > 20) {
            toast("银行卡号不合法")
            return@OnClickListener
        }
        if (telStr == null || !telStr.matches(Constant.Regex.TEL.toRegex())){
            toast("手机号码不合法")
            return@OnClickListener
        }
        GlobalScope.launch(Dispatchers.Main) {
            showLoading.call()
            val result = GlobalScope.async(Dispatchers.IO) {
                tryRun {
                    HttpClient.httpApi.addBankCard(nameStr, cardNumStr, telStr,idCard).execute()
                }
            }
            val body = result.await()?.body()
            showSuccess.call()
            if (body?.code == 0) {
                toast("添加银行卡成功")
                val userDescBean = MyApplication.userInfo.get()
//                userDescBean?.real_name = "yes"
                MyApplication.userInfo.set(userDescBean)
                MyActivityManager.getActivity(RealNameActivity::class.java)?.finish()
                if (userDescBean?.pay_password == "no"){
                    goSetPwd()
                }
                finish()
            }
        }
    }

    override fun initial() {
        super.initial()
        name.set(realName)
    }

}